import 'dart:async';

import 'package:e_reception_flutter/common_widgets/common_red_num_widget/common_red_num_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/check_in_record_brower_page.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_index/widgets/check_in_record_switch_dialog.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/check_in_rec_history_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'bean/check_in_record_index_group_info_response_bean.dart';
import 'check_in_record_index_view_model.dart';
import 'widgets/check_in_record_index_choose_date_bar_widget.dart';
import 'widgets/check_in_record_index_tab_bar_views_widget.dart';
import 'widgets/check_in_record_index_tabs_widget.dart';
import 'widgets/check_in_record_index_top_bar_widget.dart';
import 'widgets/check_in_record_index_top_filter_widget.dart';
import 'widgets/check_in_record_index_top_statistics_card_widget.dart';

/// 打卡记录首页
///
/// @author: zengxiangxi
/// @createTime: 1/8/21 2:35 PM
/// @specialDemand:
class CheckInRecordIndexPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CheckInRecordIndexPage";

  @override
  CheckInRecordIndexPageState createState() => CheckInRecordIndexPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      CheckInRecordIndexPage(),
      routeName: CheckInRecordIndexPage.ROUTER,
    );
  }
}



class CheckInRecordIndexPageState extends BaseState<CheckInRecordIndexPage>
    with TickerProviderStateMixin,NavigatorPageMixin {
  CheckInRecordIndexViewModel _viewModel;
  List<GroupInfoBean> _tabsList;

  TabController _tabController;

  bool isFirst = true;

  HsnInfoBean _selectHsBean = CheckInRecordSwitchDialog.getAllTerminalItemBean();

  StreamController<Null> multiRefreshStreamController;

  DateTime currentDateTime = DateTime.now();

  bool isSameDay = true;

  String _bytday = "今天/";

  ///获取state
  static CheckInRecordIndexPageState of(BuildContext context){
    final CheckInRecordIndexPageState result = context.findAncestorStateOfType<CheckInRecordIndexPageState>();
    return result;
  }

  @override
  void initState() {
    super.initState();
    _viewModel = CheckInRecordIndexViewModel(this);
    multiRefreshStreamController = StreamController.broadcast();
    _tabController = TabController(length: _tabsList?.length ?? 0, vsync: this);
    _viewModel?.getTopInfoHttp(_getHsn(),currentDateTime);
    // addPageListener(onPop: (){
    //   _noticeRefreshHttp();
    // });
  }

  @override
  void dispose() {
    _tabController?.dispose();
    multiRefreshStreamController?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: ValueListenableBuilder(
        valueListenable: _viewModel?.groupInfoValueNotifier,
        builder: (BuildContext context,
            CheckInRecordIndexGroupInfoDataBean groupInfoBean, Widget child) {
          if (groupInfoBean != null && isFirst) {
            isFirst = false;
            _tabsList = groupInfoBean?.groupInfo;
            _tabController =
                TabController(length: _tabsList?.length ?? 0, vsync: this);
          }

          return _toMainColumnWidget(groupInfoBean);
        },
      ),
    );
  }

  Widget _toMainColumnWidget(
      CheckInRecordIndexGroupInfoDataBean groupInfoBean) {
    return Column(
      children: <Widget>[
        _toTopBarWidget(groupInfoBean),
        CheckInRecordIndexTopFilterWidget(
          groupInfoBean: groupInfoBean,
          selectedHsnBean: _selectHsBean,
          onChanged: (HsnInfoBean newHsnInfoBean) {
            _selectHsBean = newHsnInfoBean;
           _noticeRefreshHttp();
            setState(() { });
          },
        ),
        CheckInRecordIndexTabsWidget(
          tabsList: groupInfoBean?.groupInfo,
          tabController: _tabController,
        ),
        Expanded(
          child: _toPlaceHolderWidget(groupInfoBean),
        ),
        _moreRecordsBar(groupInfoBean)
      ],
    );
  }
  
  void _noticeRefreshHttp(){
    print("请求更新");
    _viewModel?.getTopInfoHttp(_getHsn(),currentDateTime);
    Future.delayed(Duration(milliseconds: 100),(){
      multiRefreshStreamController?.add(null);
    });
  }

  Widget _toPlaceHolderWidget(CheckInRecordIndexGroupInfoDataBean groupInfoBean) {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.statusValueNotifier,
      builder:
          (BuildContext context, PlaceHolderStatusType value, Widget child) {
        return VgPlaceHolderStatusWidget(
          loadingStatus: value == PlaceHolderStatusType.loading,
          emptyStatus: groupInfoBean?.groupInfo == null || groupInfoBean.groupInfo.isEmpty,
          errorStatus: value == PlaceHolderStatusType.error,
          errorOnClick: () => _viewModel.getTopInfoHttp(_getHsn(),currentDateTime),
          loadingOnClick: () => _viewModel.getTopInfoHttp(_getHsn(),currentDateTime),
          emptyOnClick: () => _viewModel.getTopInfoHttp(_getHsn(),currentDateTime),
          child: child,
        );
      },
      child: CheckInRecordIndexTabBarViewsWidget(
        tabsList: _tabsList,
        tabController: _tabController,
        hsn: _getHsn(),
      ),
    );
  }

  ///TopBar
  Widget _toTopBarWidget(CheckInRecordIndexGroupInfoDataBean groupInfoBean) {
    return VgTopBarWidget(
      isShowBack: true,
      title: "${_bytday}${currentDateTime.month}月${currentDateTime.day}日",
      centerWidget: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              //day--
              isSameDay = false;
              currentDateTime = currentDateTime.subtract(Duration(hours: 24));
              int differDay = DateTime.now().day - currentDateTime.day;
              if (currentDateTime.month == DateTime.now().month) {
                switch (differDay) {
                  case 0:
                    _bytday = "今天/";
                    break;
                  case 1:
                    _bytday = "昨天/";
                    break;
                  case 2:
                    _bytday = "前天/";
                    break;
                  default:
                    _bytday = "";
                }
              }
              _noticeRefreshHttp();
              setState(() {});
            },
            child: Container(
              height: 44,
              padding: const EdgeInsets.only(left: 20),
              alignment: Alignment.centerRight,
              child: Image.asset(
                "images/calendar_previous_ico.png",
                height: 20,
              ),
            ),
          ),
          SizedBox(
            width: 4,
          ),
          Container(
            width: 116,
            // color: Colors.red,
            child: Center(
              child: Text(
                "${_bytday}${currentDateTime.month}月${currentDateTime.day}日",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 17),
              ),
            ),
          ),
          SizedBox(
            width: 4,
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              // day ++;
              if (!DateTime(currentDateTime.year,currentDateTime.month,currentDateTime.day).isAtSameMomentAs(DatetimeExtension.getNowInitDateTime())) {
                  currentDateTime = currentDateTime.add(Duration(hours: 24));
              }
              int differDay = DateTime.now().day - currentDateTime.day;
              if (currentDateTime.month == DateTime.now().month) {
                switch (differDay) {
                  case 0:
                    _bytday = "今天/";
                    break;
                  case 1:
                    _bytday = "昨天/";
                    break;
                  case 2:
                    _bytday = "前天/";
                    break;
                  default:
                    _bytday = "";
                }
              }
              if (DateTime(currentDateTime.year,currentDateTime.month,currentDateTime.day).isAtSameMomentAs(DatetimeExtension.getNowInitDateTime())) {
                isSameDay = true;
                // _noticeRefreshHttp();
              }
              _noticeRefreshHttp();
              setState(() {});
            },
            child: Opacity(
              opacity: isSameDay ? 0.3 : 1,
              child: Container(
                  height: 44,
                  alignment: Alignment.centerLeft,
                  padding: const EdgeInsets.only(right: 20),
                  child: Image.asset("images/calendar_next_ico.png", height: 20)),
            ),
          )
        ],
      ),

      // rightWidget: GestureDetector(
      //   behavior: HitTestBehavior.translucent,
      //   onTap: () {
      //     CheckInRecordBrowerPage.navigatorPush(context)..then((value) => _noticeRefreshHttp());
      //   },
      //   child: Row(
      //     mainAxisSize: MainAxisSize.min,
      //     children: <Widget>[
      //       Text(
      //         "未标记",
      //         maxLines: 1,
      //         overflow: TextOverflow.ellipsis,
      //         style: TextStyle(
      //             color:
      //                 ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
      //             fontSize: 12,
      //             height: 1.2),
      //       ),
      //       Padding(
      //         padding: const EdgeInsets.only(left: 4),
      //         child: CommonRedNumWidget(groupInfoBean?.unSignCnt ?? 0),
      //       )
      //     ],
      //   ),
      // ),
    );
  }

  String _getHsn() {
    if (_selectHsBean == null || StringUtils.isEmpty(_selectHsBean?.hsn)) {
      return null;
    }
    if (_selectHsBean.hsn == CHECK_IN_RCORD_DEFAULT_TERMINAL_HSN) {
      return null;
    }
    return _selectHsBean?.hsn;
  }

  ///更多记录
  Widget _moreRecordsBar(CheckInRecordIndexGroupInfoDataBean groupInfoBean) {
    if(groupInfoBean!=null&&groupInfoBean.groupInfo!=null){
      int count=0;
      groupInfoBean.groupInfo.forEach((element) {
        count+=element.cnt??0;
      });
      if(count==0){
        return SizedBox();
      }
      return GestureDetector(child: Container(
        height: 50,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Image.asset('images/lishi.png', width: 18),
            SizedBox(width: 8,),
            Text(
              '更多记录',
              style: TextStyle(fontSize: 17, color: Colors.white),
            ),
            Spacer(),
            Image.asset(
              "images/index_arrow_ico.png",
              width: 6,
              color: Colors.white,
            )
          ],
        ),
        decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF()),
        padding: EdgeInsets.symmetric(horizontal: 15),
      ),
        onTap: (){
          CheckInRecHistoryPage.navigatorPush(context);
        },);
    }else{
      return SizedBox();
    }

  }
}

extension DatetimeExtension on DateTime{

  static DateTime getNowInitDateTime(){
    final DateTime nowDateTime = DateTime.now();
    return DateTime(nowDateTime.year,nowDateTime.month,nowDateTime.day);
  }

}